<template>
  <div class="settings">
    <el-row :gutter="20">
      <!-- 站点基本信息 -->
      <el-col :span="12">
        <el-card>
          <div slot="header">
            <span>站点基本信息</span>
          </div>
          <el-form :model="siteForm" :rules="siteRules" ref="siteForm" label-width="120px">
            <el-form-item label="站点名称" prop="siteName">
              <el-input v-model="siteForm.siteName" placeholder="请输入站点名称"></el-input>
            </el-form-item>
            <el-form-item label="站点描述" prop="siteDescription">
              <el-input
                type="textarea"
                v-model="siteForm.siteDescription"
                placeholder="请输入站点描述"
                :rows="3"
              ></el-input>
            </el-form-item>
            <el-form-item label="站点LOGO" prop="logo">
              <el-upload
                class="avatar-uploader"
                action="#"
                :show-file-list="false"
                :on-success="handleLogoSuccess"
                :before-upload="beforeLogoUpload"
              >
                <img v-if="siteForm.logo" :src="siteForm.logo" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
            <el-form-item label="联系邮箱" prop="contactEmail">
              <el-input v-model="siteForm.contactEmail" placeholder="请输入联系邮箱"></el-input>
            </el-form-item>
            <el-form-item label="版权信息" prop="copyright">
              <el-input v-model="siteForm.copyright" placeholder="请输入版权信息"></el-input>
            </el-form-item>
            <el-form-item label="ICP备案" prop="icp">
              <el-input v-model="siteForm.icp" placeholder="请输入ICP备案号"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="saveSiteInfo">保存站点信息</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>

      <!-- 系统配置 -->
      <el-col :span="12">
        <el-card>
          <div slot="header">
            <span>系统配置</span>
          </div>
          <el-form :model="systemForm" :rules="systemRules" ref="systemForm" label-width="120px">
            <el-form-item label="允许注册">
              <el-switch v-model="systemForm.allowRegister"></el-switch>
            </el-form-item>
            <el-form-item label="邮箱验证">
              <el-switch v-model="systemForm.emailVerify"></el-switch>
            </el-form-item>
            <el-form-item label="题目审核">
              <el-switch v-model="systemForm.questionReview"></el-switch>
            </el-form-item>
            <el-form-item label="最大上传大小(MB)" prop="maxUploadSize">
              <el-input-number v-model="systemForm.maxUploadSize" :min="1" :max="100"></el-input-number>
            </el-form-item>
            <el-form-item label="会话超时(分钟)" prop="sessionTimeout">
              <el-input-number v-model="systemForm.sessionTimeout" :min="5" :max="1440"></el-input-number>
            </el-form-item>
            <el-form-item label="默认分页大小" prop="pageSize">
              <el-select v-model="systemForm.pageSize">
                <el-option label="10" value="10"></el-option>
                <el-option label="20" value="20"></el-option>
                <el-option label="50" value="50"></el-option>
                <el-option label="100" value="100"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="saveSystemConfig">保存系统配置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px;">
      <!-- API调试 -->
      <el-col :span="12">
        <el-card>
          <div slot="header">
            <span>API调试</span>
          </div>
          <el-form :model="apiForm" ref="apiForm" label-width="120px">
            <el-form-item label="API密钥">
              <el-input v-model="apiForm.apiKey" placeholder="请输入API密钥" show-password></el-input>
            </el-form-item>
            <el-form-item label="API地址">
              <el-input v-model="apiForm.apiUrl" placeholder="请输入API地址"></el-input>
            </el-form-item>
            <el-form-item label="测试接口">
              <el-input v-model="apiForm.testEndpoint" placeholder="请输入测试接口路径"></el-input>
            </el-form-item>
            <el-form-item label="请求参数">
              <el-input
                type="textarea"
                v-model="apiForm.requestParams"
                placeholder="请输入请求参数（JSON格式）"
                :rows="4"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="testApi">测试API</el-button>
              <el-button @click="clearApiResult">清空结果</el-button>
            </el-form-item>
            <el-form-item label="响应结果" v-if="apiForm.responseResult">
              <el-input
                type="textarea"
                v-model="apiForm.responseResult"
                :rows="6"
                readonly
              ></el-input>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>

      <!-- 数据备份 -->
      <el-col :span="12">
        <el-card>
          <div slot="header">
            <span>数据备份</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="createBackup">
              立即备份
            </el-button>
          </div>
          <el-form :model="backupForm" ref="backupForm" label-width="120px">
            <el-form-item label="自动备份">
              <el-switch v-model="backupForm.autoBackup"></el-switch>
            </el-form-item>
            <el-form-item label="备份频率">
              <el-select v-model="backupForm.backupFrequency">
                <el-option label="每天" value="daily"></el-option>
                <el-option label="每周" value="weekly"></el-option>
                <el-option label="每月" value="monthly"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="保留备份数">
              <el-input-number v-model="backupForm.keepBackups" :min="1" :max="100"></el-input-number>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="saveBackupConfig">保存备份配置</el-button>
            </el-form-item>
          </el-form>
          
          <div style="margin-top: 20px;">
            <h4>备份历史</h4>
            <el-table :data="backupList" border style="width: 100%">
              <el-table-column prop="name" label="备份文件" width="200"></el-table-column>
              <el-table-column prop="size" label="大小" width="100"></el-table-column>
              <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
              <el-table-column label="操作" width="150" align="center">
                <template slot-scope="scope">
                  <el-button size="mini" type="primary" @click="downloadBackup(scope.row)">下载</el-button>
                  <el-button size="mini" type="danger" @click="deleteBackup(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px;">
      <!-- 系统日志 -->
      <el-col :span="24">
        <el-card>
          <div slot="header">
            <span>系统日志</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="refreshLogs">
              刷新日志
            </el-button>
          </div>
          <el-form :model="logForm" ref="logForm" label-width="120px" inline>
            <el-form-item label="日志级别">
              <el-select v-model="logForm.logLevel">
                <el-option label="全部" value="all"></el-option>
                <el-option label="错误" value="error"></el-option>
                <el-option label="警告" value="warn"></el-option>
                <el-option label="信息" value="info"></el-option>
                <el-option label="调试" value="debug"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="保留天数">
              <el-input-number v-model="logForm.logRetention" :min="1" :max="365"></el-input-number>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="saveLogConfig">保存日志配置</el-button>
              <el-button @click="exportLogs">导出日志</el-button>
            </el-form-item>
          </el-form>
          
          <div style="margin-top: 20px;">
            <h4>最近日志</h4>
            <el-table :data="recentLogs" border style="width: 100%">
              <el-table-column prop="time" label="时间" width="180"></el-table-column>
              <el-table-column prop="level" label="级别" width="100" align="center">
                <template slot-scope="scope">
                  <el-tag :type="getLogLevelType(scope.row.level)">{{ scope.row.level.toUpperCase() }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="message" label="消息"></el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
export default {
  name: 'AdminSettings',
  data() {
    return {
      siteForm: {
        siteName: '题库管理系统',
        siteDescription: '专业的在线题库管理系统，支持多种题型，提供丰富的学习功能。',
        logo: '',
        contactEmail: 'admin@example.com',
        copyright: '© 2024 题库管理系统. All rights reserved.',
        icp: '京ICP备12345678号'
      },
      siteRules: {
        siteName: [
          { required: true, message: '请输入站点名称', trigger: 'blur' }
        ],
        contactEmail: [
          { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
        ]
      },
      systemForm: {
        allowRegister: true,
        emailVerify: false,
        questionReview: true,
        maxUploadSize: 10,
        sessionTimeout: 30,
        pageSize: '20'
      },
      systemRules: {
        maxUploadSize: [
          { required: true, message: '请输入最大上传大小', trigger: 'blur' }
        ],
        sessionTimeout: [
          { required: true, message: '请输入会话超时时间', trigger: 'blur' }
        ]
      },
      apiForm: {
        apiKey: 'sk-1234567890abcdef',
        apiUrl: 'https://api.example.com',
        testEndpoint: '/api/questions',
        requestParams: '{\n  "page": 1,\n  "size": 10,\n  "category": "javascript"\n}',
        responseResult: ''
      },
      backupForm: {
        autoBackup: true,
        backupFrequency: 'daily',
        keepBackups: 30
      },
      backupList: [
        {
          name: 'backup_2024_01_15_10_30_00.sql',
          size: '15.2MB',
          createTime: '2024-01-15 10:30:00'
        },
        {
          name: 'backup_2024_01_14_10_30_00.sql',
          size: '14.8MB',
          createTime: '2024-01-14 10:30:00'
        },
        {
          name: 'backup_2024_01_13_10_30_00.sql',
          size: '14.5MB',
          createTime: '2024-01-13 10:30:00'
        }
      ],
      logForm: {
        logLevel: 'info',
        logRetention: 30
      },
      recentLogs: [
        {
          time: '2024-01-15 10:30:00',
          level: 'info',
          message: '用户 admin 登录系统'
        },
        {
          time: '2024-01-15 10:25:00',
          level: 'warn',
          message: '检测到异常登录尝试'
        },
        {
          time: '2024-01-15 10:20:00',
          level: 'error',
          message: '数据库连接失败'
        },
        {
          time: '2024-01-15 10:15:00',
          level: 'info',
          message: '系统启动完成'
        }
      ]
    }
  },
  methods: {
    handleLogoSuccess(res, file) {
      this.siteForm.logo = URL.createObjectURL(file.raw);
    },
    beforeLogoUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    saveSiteInfo() {
      this.$refs.siteForm.validate((valid) => {
        if (valid) {
          this.$message.success('站点信息保存成功');
        }
      });
    },
    saveSystemConfig() {
      this.$refs.systemForm.validate((valid) => {
        if (valid) {
          this.$message.success('系统配置保存成功');
        }
      });
    },
    async testApi() {
      try {
        // 调用实际的API测试
        const response = await fetch(this.apiForm.testEndpoint, {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json'
          }
        });
        
        const result = await response.json();
        this.apiForm.responseResult = JSON.stringify(result, null, 2);
        this.$message.success('API测试完成');
      } catch (error) {
        this.apiForm.responseResult = JSON.stringify({
          code: 500,
          message: 'API测试失败: ' + error.message,
          data: null
        }, null, 2);
        this.$message.error('API测试失败');
      }
    },
    clearApiResult() {
      this.apiForm.responseResult = '';
    },
    createBackup() {
      this.$message.success('备份创建成功');
    },
    saveBackupConfig() {
      this.$message.success('备份配置保存成功');
    },
    downloadBackup(backup) {
      this.$message.success(`开始下载备份文件: ${backup.name}`);
    },
    deleteBackup(backup) {
      this.$confirm(`确定要删除备份文件 ${backup.name} 吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message.success('备份文件删除成功');
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    saveLogConfig() {
      this.$message.success('日志配置保存成功');
    },
    refreshLogs() {
      this.$message.success('日志刷新成功');
    },
    exportLogs() {
      this.$message.success('日志导出成功');
    },
    getLogLevelType(level) {
      const levelMap = {
        error: 'danger',
        warn: 'warning',
        info: 'info',
        debug: 'success'
      };
      return levelMap[level] || 'info';
    }
  }
}
</script>

<style scoped>
.settings {
  padding: 20px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>
